package avicit.bdp.dcs.utils.api.header;

import avicit.bdp.common.dto.api.KeyValue;
import avicit.bdp.dcs.utils.api.Configuration;
import avicit.bdp.dcs.utils.api.enums.Key;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.util.ArrayList;
import java.util.List;

public class GetHeaderAdapter extends HeaderAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(GetHeaderAdapter.class);

    private static GetHeaderAdapter instance;

    private GetHeaderAdapter() {
    }

    public synchronized static GetHeaderAdapter instance() {
        if (instance == null) {
            instance = new GetHeaderAdapter();
        }
        return instance;
    }

    /**
     * 构建Header请求头信息
     * @param readerSliceConfig
     * @return
     */
    public Object buildHttpEntity(Configuration readerSliceConfig){
        // 创建一个头部对象
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/json;charset=UTF-8"));

        List<MediaType> mediaTypeList = new ArrayList<>();
        mediaTypeList.add(MediaType.ALL);
        headers.setAccept(mediaTypeList);

        List<KeyValue> headerList = readerSliceConfig.getList(Key.HEADER, KeyValue.class);
        if (!CollectionUtils.isEmpty(headerList)) {
            for(int i = 0; i < headerList.size(); i++){
                KeyValue k = JSONObject.parseObject(JSONObject.toJSONString(headerList.get(i)), KeyValue.class);
                headers.add(k.getName(), k.getValue());
            }
        }

        // 追加权限认证参数
        appendAuthParam(readerSliceConfig, headers);

        return new HttpEntity<Object>(null, headers);
    }

}
